# -*- coding: utf-8 -*-
'''
@author: Johnny
@Created on: 2011-5-19
@version: 2011.5.19
@summary: Definition of iniOperator class
'''
from __future__ import with_statement
import ConfigParser, os
from util import Util

rootpath = Util.get_root_path()


class IniOperator(object):
    '''
    Ini file related operation.
    '''
    def __init__(self, file):
        '''
        Constructor.
        Keyword arguments:
        file -- ini file name
        '''
        self.cp = ConfigParser.ConfigParser()
        if not os.path.exists(file):
            f = open(file, 'a')
            f.close()
        self.cp.read(file)
        
    def getValue(self, section, option):
        '''
        Get value from ini file.
        Keyword arguments:
        section -- section name, e.g. email
        option -- option name, e.g. host
        '''
        value = self.cp.get(section, option)
        return value
    
    def setValue(self, section, option, value):
        '''
        Set value to ini file.
        Keyword arguments:
        section -- section name, e.g. email
        option -- option name, e.g. host
        value -- value to be set to ini file
        '''
        self.cp.set(section, option, value)
        with open((rootpath + "\\conf.ini"), 'w') as file:
            self.cp.write(file)
    
    def removeAll(self, section):
        '''
        Remove section from ini file.
        Keyword arguments:
        section -- section name, e.g. email
        '''
        options = self.cp.options(section)
        for option in options:
            self.cp.remove_option(section, option)
        with open((rootpath + "\\conf.ini"), 'w') as file:
            self.cp.write(file)
    
    def storeFeeds(self, list, path):
        '''
        Store feeds to ini file.
        Keyword arguments:
        list -- feed list
        path -- file name to be saved
        '''
        if not self.cp.has_section('feeds'):
            self.cp.add_section('feeds')
            
        ids = self.cp.options('feeds')
        if len(ids):
            for id in ids:
                self.cp.remove_option('feeds', id)
        for meta in list:
            self.cp.set('feeds', meta[0], meta[1].encode('utf-8'))
            
        with open((path), 'w') as file:
            self.cp.write(file) 
        
    def optionsToList(self):
        '''
        Convert ini file options to a list.
        '''
        list = []
        ids = self.cp.options('feeds')
        if len(ids):
            for id in ids:
                temp = []
                temp.append(id)
                temp.append((self.cp.get('feeds', id)).decode('utf-8'))
                list.append(temp)
        return list
        
        